package com.dong.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author dongjian
 * 延迟队列（插件）配置类
 */
@Configuration
public class DelayedQueueConfig {

    /**
     * 延迟队列交换机名称
     */
    public static final String DELAYED_EXCHANGE_NAME = "delayed.exchange";
    /**
     * 延迟队列名称
     */
    public static final String DELAYED_QUEUE_NAME = "delayed.queue";
    /**
     * 延迟队列routingKey
     */
    public static final String DELAYED_ROUTING_KEY = "delayed.routingKey";

    /**
     * 声明交换机
     */
    @Bean
    public CustomExchange delayedExchange() {
        Map<String, Object> arguments = new HashMap<>(3);
        // 设置延迟交换机类型
        arguments.put("x-delayed-type", "direct");
        /**
         * 参数说明：
         * 1.交换机名称
         * 2.交换机类型
         * 3.是否持久化
         * 4.是否自动删除
         * 5.其他参数
         */
        return new CustomExchange(DELAYED_EXCHANGE_NAME, "x-delayed-message", true,
                false, arguments);
    }

    /**
     * 声明队列
     *
     * @return {@link Queue}
     */
    @Bean
    public Queue delayedQueue() {
        return QueueBuilder.durable(DELAYED_QUEUE_NAME).build();
    }

    /**
     * 绑定
     * @return {@link Binding}
     */
    @Bean
    public Binding delayedQueueBindDelayedExchange(@Qualifier("delayedQueue") Queue delayedQueue,
                                                   @Qualifier("delayedExchange") CustomExchange delayedExchange) {
        return BindingBuilder.bind(delayedQueue).to(delayedExchange).with(DELAYED_ROUTING_KEY).noargs();
    }
}
